package com.apes.fn.server.productRequireManage.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productRequire.ProductRequire;
import com.apes.fn.server.productRequire.ProductRequireRepository;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service("requirePurchasePriceService")
public class RequirePurchasePriceService extends DomainService {
    @Autowired
    private ProductRequireRepository requireRepository;

    public JSONArray obtainXJZXBPriceAccordiOrderId(JSONObject condiOther) {
        if (StringUtils.isEmpty(condiOther.getString("commodityInquiryOrderId"))) return new JSONArray();
        String supplierId = condiOther.getString("supplierId");
        Map condi = new HashMap();
        condi.put("conditionStrategyId", "CG04");
        condi.put("PRODUCT_ID", condiOther.get("productId"));
        condi.put("SYS_RQ", new Date());
        condi.put("XJDH", condiOther.getString("commodityInquiryOrderId"));
        condi.put("SOURCE", condiOther.getString("source"));
        condi.put("SUPPLIER_ID", supplierId.startsWith("0")?"00" + supplierId:supplierId);

        condi.put("CGZID", condiOther.get("purchasingGroupId"));
        condi.put("PTID", condiOther.get("platformId"));
        condi.put("WYZ", condiOther.get("uniqueValue"));

        return this.findZXBPrice(condi);
    }

    public JSONArray obtainXJZXBPriceAccordCompany(JSONObject condiOther) {
        Map condi = new HashMap();
        condi.put("conditionStrategyId", "CG04");
        condi.put("PRODUCT_ID", condiOther.get("productId"));
        condi.put("SYS_RQ", new Date());
        condi.put("SOURCE", condiOther.getString("source"));
        condi.put("COMPANY_ID", condiOther.get("companyId"));
        condi.put("CGZID", condiOther.get("purchasingGroupId"));
        condi.put("PTID", condiOther.get("platformId"));
        return this.findZXBPrice(condi);
    }

    private JSONArray findZXBPrice(Map condi) {
        try {
            Object priceResult = this.invoke("condition.execConditionStrategy_trans", condi);
            JSONArray priceArray = JSONObject.parseObject(priceResult.toString()).getJSONArray("getSPXJDZXBPrice");
            if (!ObjectUtils.isEmpty(priceArray)) {
                priceArray.forEach(singlePrice -> {
                    JSONObject priceObj = (JSONObject) singlePrice;
                    priceObj.put("SUPPLIER_ID", this.supplierLenCovert(priceObj.getString("SUPPLIER_IDS")));
                });
            }
            return priceArray;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONArray();
    }

    private JSONArray findZXBPriceMuti(Map condi) {
        try {
            Object priceResult = this.invoke("condition.getCondition_Muti", condi);
            if (ObjectUtils.isEmpty(priceResult)) return new JSONArray();
            JSONArray priceArray = JSON.parseArray(priceResult.toString());
            return priceArray;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONArray();
    }

    // 供应商长度转换
    private String supplierLenCovert(String peiceSupplierId) {
        return peiceSupplierId.length() == 8?peiceSupplierId.substring(2, 8):peiceSupplierId;
    }


    // 获取策略价格
    public JSONArray obtainStrategyPrice(JSONObject priceCondiOther) {
        String productId = priceCondiOther.getString("productId");
        Map getPriceParam = new HashMap();
        getPriceParam.put("SYS_RQ", new Date());
        getPriceParam.put("conditionId", "T03");
        getPriceParam.put("PRODUCT_ID", productId);
        getPriceParam.put("BRAND_ID", priceCondiOther.getString("brandId"));
        getPriceParam.put("CLASSIFY_ID", priceCondiOther.getString("classifyId"));
        getPriceParam.put("SYS_DIM_FIELD", "PRODUCT_ID");
        getPriceParam.put("SYS_NO_CHECK", "SUPPLIER_ID,COMPANY_ID,CAR_LICENSE");
        JSONArray strategyPriceArrary = this.findZXBPriceMuti(getPriceParam);
        return strategyPriceArrary;

    }

    // 获取区域价格
    public JSONArray obtainAccessPrice(String productId, String companyId) {
        // 区域价格 - 接入商
        AccessProvider accessProvider = SpringManager.getBean(AccessProviderRepository.class).findByCompany(companyId);
        Map accessPriceCondi = new HashMap();
        accessPriceCondi.put("SYS_RQ", new Date());
        accessPriceCondi.put("conditionId", "T04");
        accessPriceCondi.put("PRODUCT_ID", productId);
        accessPriceCondi.put("ACCESS_PROVIDER_ID", accessProvider.getId());
        accessPriceCondi.put("SYS_DIM_FIELD", "PRODUCT_ID,ACCESS_PROVIDER_ID");
        accessPriceCondi.put("SYS_NO_CHECK", "SUPPLIER_ID");
        JSONArray accessProviderPriceArray = this.findZXBPriceMuti(accessPriceCondi);
        if (!accessProviderPriceArray.isEmpty()) {
            accessProviderPriceArray.forEach(accessPriceSingle -> {((JSONObject) accessPriceSingle).put("COMPANY_ID", companyId);});
        }

        // 区域价格 - 公司
        accessPriceCondi.remove("ACCESS_PROVIDER_ID");
        accessPriceCondi.put("COMPANY_ID", companyId);
        accessPriceCondi.replace("SYS_DIM_FIELD", "PRODUCT_ID,COMPANY_ID");
        JSONArray t04CompanyArray = this.findZXBPriceMuti(accessPriceCondi);

        accessProviderPriceArray.addAll(t04CompanyArray);
        return accessProviderPriceArray;
    }

    // 要货单 - 获取来源单据上的价格
    private Map obtainServicePlanOrLossQuoPrice(JSONObject condi) {
        String channelType = condi.getString("channelType");
        String sourceBusinessType = condi.getString("sourceBusinessType");
        sourceBusinessType = sourceBusinessType != null?sourceBusinessType.toUpperCase():"";
        if (StringUtils.isEmpty(sourceBusinessType) || StringUtils.isEmpty(channelType)
                || LogicalUtil.notIn(channelType, "1", "4") || LogicalUtil.notIn(sourceBusinessType, "ServicePlan".toUpperCase(), "LossQuotation".toUpperCase())) return new HashMap();

        String supplierId = condi.getString("supplierId");
        String productId = condi.getString("productId");
        String source = condi.getString("source");
        Map documentPrice = getBean(ServicePlanItemRepository.class).findByPrice(source, productId, supplierId);
        Map returnPrice = new HashMap();
        if (!documentPrice.isEmpty()) {
            returnPrice.putAll(documentPrice);
            returnPrice.putAll(MapUtil.mapper("PRODUCT_ID", productId, "uniqueValue", documentPrice.get("UNIQUEVALUE")));
        }
        return returnPrice;
    }

    // 获取供应商平台的价格
    private JSONArray obtainSupplierPlatformPrice(JSONObject condi) {
        if (LogicalUtil.notIn(condi.getString("channelType"), "2", "5")) return new JSONArray();
        ProductRequire require =  requireRepository.findOne(condi.getString("productRequireId"));
        String productId = condi.getString("productId");
        Map data = new HashMap();
        data.put("vin", require.getCustomerExpand().getVin());
        data.put("id", require.getLocation().getDepot().getDept().getId());
        data.put("offerId", condi.getString("offerId"));
        JSONObject supplierResult = JSONObject.parseObject(invoke("sp.SpProduct.enquiryVin", data));
        JSONArray prices = supplierResult.getJSONArray("body");
        prices.stream().forEach(price -> {
            JSONObject priceO = (JSONObject) price;
            priceO.put("XJDH", priceO.getString("enquiryId"));
            priceO.put("uniqueValue", priceO.getString("uniqueValue"));
            priceO.put("PRODUCT_ID", productId);
            priceO.put("priceSource", "supplierPlatformPrice");
        });
        return prices;
    }



    // 价格汇总返回
    public Set<Map> replinishPurchasePriceSumm(JSONObject item) {
        JSONObject priceCondi = this.appendZXBCondi(item);
        JSONArray accordOrderIdFindZXBPrices = this.obtainXJZXBPriceAccordiOrderId(priceCondi);
        JSONArray accordCompanyIdFindZXBPrices = this.obtainXJZXBPriceAccordCompany(priceCondi);
        JSONArray accordStrategyPrices = this.obtainStrategyPrice(priceCondi);
        JSONArray accessProviderPrices = this.obtainAccessPrice(priceCondi.getString("productId"), priceCondi.getString("companyId"));
        Map servicePlanAndLossQuoPrice = this.obtainServicePlanOrLossQuoPrice(priceCondi);
        JSONArray supplierPlatformPrices = this.obtainSupplierPlatformPrice(priceCondi);

        Set newPriceItem = new HashSet<>();
        newPriceItem.addAll(this.filterPriceColumn(accordOrderIdFindZXBPrices, "ZXB"));
        newPriceItem.addAll(this.filterPriceColumn(accordCompanyIdFindZXBPrices, "ZXB"));
        newPriceItem.addAll(this.filterPriceColumn(accordStrategyPrices, "strategy"));
        newPriceItem.addAll(this.filterPriceColumn(accessProviderPrices, "strategy"));
        if (!servicePlanAndLossQuoPrice.isEmpty()) {
            servicePlanAndLossQuoPrice.put("priceSource", "documentPrice");
            newPriceItem.add(servicePlanAndLossQuoPrice);
        }
        newPriceItem.addAll(supplierPlatformPrices);
        return newPriceItem;
    }

    /**
     * 过滤无效的字段
     * priceSource  (documentPrice 单据价格
     * 		         ZXB 执行表价格
     * 			     strategy 策略价格
     * 			     supplierPlatformPrice 供应商平台价格)
     */
    private Set<Map> filterPriceColumn(JSONArray priceItem, String priceSource) {
        if (Objects.isNull(priceItem)) return new HashSet<>();
        return priceItem.stream().filter(price -> {
            JSONObject priceObj = (JSONObject) price;
            return !StringUtils.isEmpty(priceObj.get("P001")) && priceObj.getDoubleValue("P001") > 0;
        }).map(price -> {
            JSONObject priceObj = (JSONObject) price;
            return MapUtil.mapper("P001", priceObj.get("P001"),
                    "PRODUCT_ID", priceObj.get("PRODUCT_ID"),
                    "SUPPLIER_ID", priceObj.get("SUPPLIER_ID"),
                    "XJBJ", priceObj.get("XJBJ"),
                    "XJDH", priceObj.get("XJDH"),
                    "priceSource", priceSource);

        }).collect(Collectors.toSet());
    }

    // 拼接执行表查询条件
    private JSONObject appendZXBCondi(JSONObject item) {
        Map condi = MapUtil.mapper("productId", item.getJSONObject("product").getString("id"),
                "commodityInquiryOrderId", item.getString("commodityInquiryOrderId"),
                "companyId", item.getJSONObject("locationCompany").getString("id"),
                "source", item.getString("source"),
                "sourceBusinessType", item.getString("sourceBusinessType"),
                "brandId", item.getString("brandId"),
                "spId", item.getString("spId"),//供应商商品ID
                "channelType", item.getString("channelType"),//渠道
                "productRequireId", item.getString("productRequireId"),
                "offerId", item.getString("offerId"),
                "classifyId", item.getString("classifyId"));
        if (!ObjectUtils.isEmpty(item.getJSONObject("purchasingGroup"))) {
            condi.put("purchasingGroupId", item.getJSONObject("purchasingGroup").getString("id"));
        } if (!ObjectUtils.isEmpty(item.getJSONObject("platform"))) {
            condi.put("platformId", item.getJSONObject("platform").getString("id"));
        } if (!ObjectUtils.isEmpty(item.getJSONObject("supplier"))) {
            condi.put("supplierId", item.getJSONObject("supplier").getString("id"));
        } if (!ObjectUtils.isEmpty(item.getJSONObject("supplier"))) {
            condi.put("supplierId", item.getJSONObject("supplier").getString("id"));
        } if (!StringUtils.isEmpty(item.get("uniqueValue"))) {
            condi.put("uniqueValue", item.get("uniqueValue"));
        }
        return new JSONObject(condi);
    }

    // 巴图鲁价格变动判断
    public boolean baturuPriceChangeJudge(Set<Map> prices, JSONObject item) {
        String channelType = item.getString("channelType");
        if (!"5".equals(channelType)) return true;
        for (Map price : prices) {
            if (!price.get("priceSource").toString().equals("supplierPlatformPrice")) continue;
            JSONObject supplierResult = JSONObject.parseObject(invoke("sp.quoteResultService.accordPriceNo", MapUtil.mapper("priceNo", price.get("priceNo"), "quoteId", price.get("quoteId"))));
            double singlePriceObj = supplierResult.getDoubleValue("body");
            double eP001 = Double.valueOf(price.get("P001").toString());

            return eP001 == singlePriceObj;
        }
        return false;
    }
}






























